package com.base.service.impl;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.base.model.CustomData;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.util.IOUtils;
import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.base.model.CustomAllot;
import com.base.service.ExcelService;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.afterturn.easypoi.excel.imports.ExcelImportService;
import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class ExcelServiceImpl implements ExcelService {

	@Override
	public List<String> customAllotImport(MultipartFile file) {
		if (file == null) {
			log.error("未获取excel文件");
		}
		ImportParams params = new ImportParams();
		params.setNeedVerfiy(true);// 打开校验功能
		try {
			// 要获取校验失败的集合或者workbook的话需要设置needMore等于true。
			ExcelImportResult importResult = new ExcelImportService().importExcelByIs(file.getInputStream(),
					CustomAllot.class, params, true);
			List<CustomAllot> failList = importResult.getFailList();
			//如果有错误数据
			if (CollectionUtils.isNotEmpty(failList)) {
				List<String> list = new ArrayList<String>();
				for (CustomAllot customAllot : failList) {
					list.add(String.format("错误行号:%s,错误原因:%s",
							customAllot.getRowNum(),customAllot.getErrorMsg()));
				}
				return list;
			}

			List<CustomAllot> customAllots = importResult.getList();
			for (CustomAllot customAllot : customAllots) {
				log.info(customAllot.toString());
			}

		} catch (Exception e) {
			log.error("excel文件解析出错,{}",e.getMessage(),e);
		}
		return null;
	}

	private static final String[] equipmentArray = { "电脑", "手机", "平板", "其他" };
	private static final String[] sourceArray = { "江苏", "上海", "北京", "天津" , "山东",
			"浙江", "安徽", "河北", "山西", "辽宁", "福建", "江西", "黑龙江"};
	private static final String[] yesOrNoArray = { "是", "否"};
	@Override
	public void customAllotExport(HttpServletResponse response,Object object) throws Exception {

		String fileName = "E:\\下载\\skuName.txt";
		BufferedReader reader = new BufferedReader(new FileReader(fileName));

		List<CustomData> list = new ArrayList<>();
		String line;
		while ((line = reader.readLine()) != null) {
			CustomData obj = new CustomData();
			obj.setUserId(new Random().nextInt(100000));
			obj.setEquipment(equipmentArray[new Random().nextInt(4)]);
			obj.setRatio(new Random().nextInt(1000));
			obj.setSource(sourceArray[new Random().nextInt(13)]);
			obj.setBrowse(yesOrNoArray[new Random().nextInt(2)]);
			obj.setBuy(yesOrNoArray[new Random().nextInt(2)]);
			obj.setMark(new Random().nextInt(10));
			obj.setAddCart(yesOrNoArray[new Random().nextInt(2)]);
			obj.setSkuSaleNum(new Random().nextInt(10000));
			obj.setSkuName(line);
			list.add(obj);
		}

		// ExportParams可以通过构造的两个参数设置导出的sheet名字和excel的title列名
		ExportParams params = new ExportParams();
		Workbook workbook = ExcelExportUtil.exportExcel(params, object.getClass(), list);
		// 告诉浏览器用什么软件可以打开此文件
		response.setHeader("content-Type", "application/vnd.ms-excel");
		// 下载文件的默认名称
		try {
			response.setHeader("Content-Disposition",
					"attachment;filename=" + URLEncoder.encode("自定义分配配置", "UTF-8") + ".xls");
			// 编码
			response.setCharacterEncoding("UTF-8");
			workbook.write(response.getOutputStream());
		} catch (Exception e) {
			log.error("编码转换出错,{}", e.getMessage(), e);
		}
	}

	@Override
	public void test(HttpServletRequest request, HttpServletResponse response) throws IOException {

		String fileUrl = "https://dianrong-mainapp-demo.oss-cn-shanghai.aliyuncs.com/CUSTOMER_MANAGEMENT/EXCEPTIONAL_POVERTY/EXCEPTIONAL_POVERTY/17282959/V1.0.0/3850/2022/07/27/qrios.png?Expires=2289625123&OSSAccessKeyId=LTAI4Fm2sdj1T7i3WxgiBWaB&Signature=0jvruQ1MwWVbHzZshTTtIUXvTos%3D";

		String filePath = request.getSession().getServletContext().getRealPath("/upload")+"/1002/";
		File file = new File(filePath);
		if (!file.exists()) {
			file.mkdirs();
		}
		for (int i = 0; i < 10; i++) {
			downloadFileToLocal(fileUrl, filePath);
		}
		// 文件夹压缩
		FolderToZipUtil.zip(filePath,1001L,response);
		if (file.exists()) {
			remove(file);
		}
	}


	/**
	 * 删除指定文件夹下的全部内容
	 * @param file
	 */
	public static void remove(File file) {
		File[] files = file.listFiles();//将file子目录及子文件放进文件数组
		if (files != null) {//如果包含文件进行删除操作
			for (int i = 0; i < files.length; i++) {
				if (files[i].isFile()) {//删除子文件
					files[i].delete();
				} else if (files[i].isDirectory()) {//通过递归方法删除子目录的文件
					remove(files[i]);
				}
				files[i].delete();//删除子目录
			}
		}
	}

	private void downloadFileToLocal(String fileUrl, String filePath) {
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		HttpURLConnection conn = null;
		try {
			URL url = new URL(fileUrl);
			conn = (HttpURLConnection) url.openConnection();
			//设置超时间为3秒
			conn.setConnectTimeout(60 * 1000);
			//防止屏蔽程序抓取而返回403错误
			conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
			//得到输入流
			InputStream inputStream = conn.getInputStream();
			bis = new BufferedInputStream(inputStream);
			String substring = fileUrl.substring(0, fileUrl.indexOf("?"));
			String fileName = substring.substring(substring.lastIndexOf("/") + 1);
			FileOutputStream fileOut = new FileOutputStream(filePath + "/" + UUID.randomUUID().toString()+fileName);
			bos = new BufferedOutputStream(fileOut);
			byte[] buf = new byte[4096];
			int length = bis.read(buf);
			//保存文件
			while(length != -1)
			{
				bos.write(buf, 0, length);
				length = bis.read(buf);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			IOCloseUtil.close(bos, bis);
			if (conn != null) {
				conn.disconnect();
			}
		}
	}



}
